import { request } from '@/utils/request'
import type {
  CreateTeamMemberPayload,
  TeamMemberListResponse,
  TeamMemberQueryParams,
  TeamMemberRecord,
  TeamMemberStatistics,
  UpdateTeamMemberPayload
} from '@/types/team-member'
import type { ProjectMemberRole } from '@/types/project'

const defaultStatistics: TeamMemberStatistics = {
  total_members: 0,
  active_members: 0,
  inactive_members: 0,
  by_role: {},
  by_project: []
}

function normalizeRecord(record: any): TeamMemberRecord {
  const roles = Array.isArray(record?.roles) ? record.roles : []
  const role_names = Array.isArray(record?.role_names) ? record.role_names : []
  const role_codes = Array.isArray(record?.role_codes) ? record.role_codes : []
  // 向后兼容：使用第一个角色代码作为主要角色
  const primaryRole = role_codes.length > 0 ? role_codes[0] : (record?.role || undefined)
  
  return {
    project: {
      id: record?.project?.id ?? record?.project_id ?? '',
      name: record?.project?.name ?? record?.project_name ?? '',
      status: record?.project?.status ?? record?.project_status ?? null,
      priority: record?.project?.priority ?? record?.project_priority ?? null,
      is_archived: Boolean(record?.project?.is_archived ?? record?.project_is_archived ?? false)
    },
    member: {
      id: record?.member?.id ?? record?.member_id ?? '',
      username: record?.member?.username ?? record?.member_username ?? null,
      name: record?.member?.name ?? record?.member_name ?? null,
      email: record?.member?.email ?? record?.member_email ?? null,
      avatar: record?.member?.avatar ?? record?.member_avatar ?? null,
      status: record?.member?.status ?? record?.member_status ?? null,
      department: record?.member?.department ?? record?.member_department ?? null,
      position: record?.member?.position ?? record?.member_position ?? null
    },
    roles,
    role_names,
    role_codes,
    role: primaryRole as ProjectMemberRole | undefined,
    permissions: Array.isArray(record?.permissions) ? record.permissions : [],
    joined_at: record?.joined_at ?? ''
  }
}

export async function getTeamMembers(params: TeamMemberQueryParams = {}): Promise<TeamMemberListResponse> {
  const queryParams: Record<string, unknown> = {}
  if (params.project_id) queryParams.project_id = params.project_id
  if (params.role) queryParams.role = params.role
  if (params.status) queryParams.status = params.status
  if (params.keyword) queryParams.keyword = params.keyword
  queryParams.page = params.page ?? 1
  queryParams.size = params.size ?? 20
  if (params.sort_by) queryParams.sort_by = params.sort_by
  if (params.sort_order !== undefined) queryParams.sort_order = params.sort_order

  const response = await request({
    url: '/team-members',
    method: 'get',
    params: queryParams
  })

  const payload = response.data?.data ?? {}
  const items = Array.isArray(payload.items) ? payload.items.map(normalizeRecord) : []
  const pagination = payload.pagination ?? {}
  const statistics: TeamMemberStatistics = {
    ...defaultStatistics,
    ...(payload.statistics ?? {})
  }

  return {
    items,
    pagination: {
      total: pagination.total ?? items.length,
      page: pagination.page ?? queryParams.page ?? 1,
      size: pagination.size ?? queryParams.size ?? 20,
      pages: pagination.pages,
      has_prev: pagination.has_prev,
      has_next: pagination.has_next
    },
    statistics
  }
}

export function addTeamMember(data: CreateTeamMemberPayload) {
  return request({
    url: '/team-members',
    method: 'post',
    data
  })
}

export function updateTeamMember(projectId: string, userId: string, data: UpdateTeamMemberPayload) {
  return request({
    url: `/team-members/${projectId}/${userId}`,
    method: 'put',
    data
  })
}

export function removeTeamMember(projectId: string, userId: string) {
  return request({
    url: `/team-members/${projectId}/${userId}`,
    method: 'delete'
  })
}



